package com.css.fxfzxczh.modules.disasterDamageInfo.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.css.fxfzxczh.base.attachment.entity.AttachmentInfoEntity;
import com.css.fxfzxczh.base.attachment.service.AttachmentInfoService;
import com.css.fxfzxczh.modules.disasterDamageInfo.entity.DisasterAssess;
import com.css.fxfzxczh.modules.disasterDamageInfo.entity.DisasterDamage;
import com.css.fxfzxczh.modules.disasterDamageInfo.repository.DisasterAssessRepository;
import com.css.fxfzxczh.modules.disasterDamageInfo.repository.DisasterDamageRepository;
import com.css.fxfzxczh.modules.disasterDamageInfo.service.DisasterService;
import com.css.fxfzxczh.modules.disasterDamageInfo.verify.DisasterAssessExcelVerify;
import com.css.fxfzxczh.modules.disasterDamageInfo.verify.DisasterDamageExcelVerify;
import com.css.fxfzxczh.modules.disasterDamageInfo.vo.DisasterAssessImportVo;
import com.css.fxfzxczh.modules.disasterDamageInfo.vo.DisasterDamageImportVo;
import com.css.fxfzxczh.modules.synthesizeInfoManage.matManage.vo.MatManageImportVo;
import com.css.fxfzxczh.util.UUIDGenerator;
import com.css.fxfzxczh.web.PlatformSessionContext;
import org.apache.poi.ss.formula.functions.T;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileInputStream;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.function.Function;

/**
 * @Author:
 * @CreateTime: 2024/4/19 15:59
 * @Description:
 */
@Service
public class DisasterServiceImpl implements DisasterService {

    @Resource
    private DisasterDamageRepository disasterDamageRepository;

    @Resource
    private DisasterAssessRepository disasterAssessRepository;


    @Resource
    private DisasterDamageExcelVerify damageExcelVerify;

    @Resource
    private DisasterAssessExcelVerify disasterAssessExcelVerify;

    @Value("${image.localDir}")
    private String localDir;

    @Resource
    private AttachmentInfoService attachmentInfoService;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void importExcel(String attachId,String category) throws Exception {
        AttachmentInfoEntity attachmentInfoEntity = attachmentInfoService.getAttach(attachId);
        String attachPath = attachmentInfoEntity.getAttachPath();
        String name = localDir  + attachPath;
        FileInputStream inputStream = new FileInputStream(new File(name));

        // 导入的参数信息
        ImportParams params = new ImportParams();
        params.setTitleRows(1);
        params.setHeadRows(1);
        String userID = PlatformSessionContext.getUserID();

        if ("0".equals(category)){
            params.setVerifyHandler(damageExcelVerify);

            ExcelImportResult<DisasterDamageImportVo> result = ExcelImportUtil.importExcelMore(inputStream, DisasterDamageImportVo.class, params);
            List<DisasterDamageImportVo> failList = result.getFailList();
            errorHandle(failList, item -> item.getRowNum(), item -> item.getErrorMsg());


            List<DisasterDamageImportVo> list = result.getList();


            List<DisasterDamage> disasterDamageList = new LinkedList<>();

            if (!CollectionUtils.isEmpty(list)) {
                list.forEach(item -> {
                    DisasterDamage disasterDamage = new DisasterDamage();
                    BeanUtils.copyProperties(item, disasterDamage);
                    disasterDamage.setId(UUIDGenerator.getUUID());
                    disasterDamage.setCreateUser(userID);
                    disasterDamage.setCreateTime(new Date());
                    Map<String, Object> map = disasterDamageRepository.getCountyInfo(item.getLongitude(),item.getLatitude());
                    disasterDamage.setCountyCode((String) map.get("code"));
                    disasterDamage.setCountyGeom((String) map.get("geom"));
                    disasterDamageList.add(disasterDamage);
                });
            }
            disasterDamageRepository.batchSave(disasterDamageList);
        }else {
            params.setVerifyHandler(disasterAssessExcelVerify);
            ExcelImportResult<DisasterAssessImportVo> result = ExcelImportUtil.importExcelMore(inputStream, DisasterAssessImportVo.class, params);
            List<DisasterAssessImportVo> failList = result.getFailList();
            errorHandle(failList, item -> item.getRowNum(), item -> item.getErrorMsg());


            List<DisasterAssessImportVo> list = result.getList();
            List<DisasterAssess> disasterAssessList = new LinkedList<>();
            list.forEach(item -> {
                DisasterAssess disasterAssess = new DisasterAssess();
                disasterAssess.setId(UUIDGenerator.getUUID());
                disasterAssess.setCreateUser(userID);
                disasterAssess.setCreateTime(new Date());
                disasterAssess.setAssessUnit(item.getAssessUnit());
                disasterAssess.setAssessNumber(item.getAssessNumber());
                disasterAssessList.add(disasterAssess);
            });
            disasterAssessRepository.batchSave(disasterAssessList);

        }



    }

    private <T> void errorHandle(List<T> failList, Function<T, Integer> getRowNum, Function<T, String> getErrorMsg) {
        StringBuilder errorMsg = new StringBuilder("<font size='5px' color='red'>导入失败：</font>");
        for (T item : failList) {
            Integer rowNum = getRowNum.apply(item);
            String errorMessage = getErrorMsg.apply(item);
            errorMsg.append("<font size='4px'><br>").append("第").append(rowNum + 1).append("行： ").append(errorMessage).append("</font>");
        }
        throw new RuntimeException(errorMsg.toString());
    }


}
